package com.springboot.study.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.springboot.study.entity.ImportExcelDTO;
import com.springboot.study.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: guodong
 * @Date: 2021/9/13 11:25
 * @Version: 1.0
 * @Description:
 */
@Slf4j
public class TianYanChaImportListener extends AnalysisEventListener<ImportExcelDTO>{

    List<ImportExcelDTO> importExcelDTOList = new ArrayList<>();
    private String tableName;
    private String tableComment;

    /**
     * 每解析一行，回调该方法
     * @param data
     * @param context
     */
    @Override
    public void invoke(ImportExcelDTO data, AnalysisContext context) {
        Integer currentRowNum = context.getCurrentRowNum();
        if(currentRowNum == 0){
            tableName = data.getColumnName().replace("自定义：", "");
            tableComment = data.getJdbcType().replace("自定义：", "");
        }else {
            importExcelDTOList.add(data);
        }
    }

    /**
     * 出现异常回调
     * @param exception
     * @param context
     * @throws Exception
     */
    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        // ExcelDataConvertException:当数据转换异常的时候，会抛出该异常，此处可以得知第几行，第几列的数据
        if (exception instanceof ExcelDataConvertException) {
            String message = null;
            try {
                Integer columnIndex = ((ExcelDataConvertException) exception).getColumnIndex() + 1;
                Integer rowIndex = ((ExcelDataConvertException) exception).getRowIndex() + 1;
                message = "第" + rowIndex + "行，第" + columnIndex + "列" + "数据格式有误，请核实";
            } catch (Exception e) {
                e.printStackTrace();
            }
            throw new RuntimeException(message);
        } else if (exception instanceof RuntimeException) {
            throw exception;
        } else {
            super.onException(exception, context);
        }
    }

    /**
     * 解析完全部回调
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if(!CollectionUtils.isEmpty(importExcelDTOList)){
            importExcelDTOList.forEach(data ->{
                data.setColumnName(data.getColumnName().replace("自定义：", ""));
                if(!org.springframework.util.StringUtils.isEmpty(data.getJdbcType())){
                    data.setJdbcType(data.getJdbcType().replace("自定义：", "").replace("init", "int"));
                }
                data.setRemark(data.getRemark().replace("自定义：", ""));
            });
        }
        saveData(tableName, tableComment, importExcelDTOList);
        importExcelDTOList.clear();
    }


    public void saveData(String tableName, String tableComment, List<ImportExcelDTO> importExcelDTOList){
        StringBuffer stringBuffer = new StringBuffer("");
        stringBuffer.append("CREATE TABLE ").append("`").append(tableName).append("`(").append("\r\n");
        stringBuffer.append("  `id` int(20) COMMENT '主键id',").append("\r\n");
        stringBuffer.append("  `tax_number` varchar(255) DEFAULT NULL COMMENT '纳税人识别号',").append("\r\n");
        stringBuffer.append("  `company_name` varchar(255) DEFAULT NULL COMMENT '公司名称',").append("\r\n");
        for(ImportExcelDTO importExcelDTO : importExcelDTOList){
            if(importExcelDTO.getColumnName().equals("id")){
                continue;
            }
            stringBuffer.append("  `").append(StringUtils.underscoreName(importExcelDTO.getColumnName()).replace("__", "_")).append("`");
            stringBuffer.append(" ").append(handleJdbcType(importExcelDTO.getJdbcType()));
            stringBuffer.append(" ").append("COMMENT");
            stringBuffer.append(" ").append("'").append(importExcelDTO.getRemark()).append("',").append("\r\n");
        }
        stringBuffer.append("  `feature` text CHARACTER SET utf8mb4 COMMENT '特征值',\n" +
                "  `operator_id` bigint(20) DEFAULT NULL COMMENT '操作人ID',\n" +
                "  `version` int(10) DEFAULT NULL COMMENT '版本号',\n" +
                "  `is_deleted` int(4) DEFAULT NULL COMMENT '删除状态 0-未删除 1-删除',\n" +
                "  `gmt_created` timestamp NULL DEFAULT NULL COMMENT '创建时间',\n" +
                "  `gmt_modified` timestamp NULL DEFAULT NULL COMMENT '修改时间',\n" +
                "  `delete_assist` bigint(255) DEFAULT '1' COMMENT '删除辅助字段，删除后值等于主键值',\n" +
                "  PRIMARY KEY (`id`) USING BTREE");
        stringBuffer.append("\r\n");
        stringBuffer.append(") ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='").append(tableComment).append("'");
        System.out.println(stringBuffer.toString());
    }


    public String handleJdbcType(String jdbcType){
        if(jdbcType == null){
            return "";
        }
        switch(jdbcType){
            case "时间戳" :
                return "timestamp";
            case "日期":
                return "timestamp";
            case "万分制" :
                return "decimal(34,20)";
            case "mediumtext":
                return "text";
            default : //可选
                return jdbcType;
        }
    }

    public List<ImportExcelDTO> getImportExcelDTOList() {
        return importExcelDTOList;
    }

    public void setImportExcelDTOList(List<ImportExcelDTO> importExcelDTOList) {
        this.importExcelDTOList = importExcelDTOList;
    }

    public String getTableName() {
        return tableName;
    }

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    public String getTableComment() {
        return tableComment;
    }

    public void setTableComment(String tableComment) {
        this.tableComment = tableComment;
    }
}
